import axios from "axios";
import { Toast, Notify } from 'vant';
import { clear, get, STORAGE_TYPES } from "./storage";
import { router } from "../router";

const http = axios.create({
    baseURL: "http://127.0.0.1:3000",
    timeout: 150000
});

http.interceptors.request.use(
    (config) => {
        config.headers = {
            ...config.headers,
            "Content-Type": "application/json",
            Authorization: `Basic ZXhhbTpMcHpKU2IzQw==`
        };
        if (get(STORAGE_TYPES.SET_TOKEN)) {
            config.headers = {
                ...config.headers,
                TokenAuthorization: get(STORAGE_TYPES.SET_TOKEN)
            };
        }
        if (!config.headers?.noLoading) {
            Toast.loading({
                duration: 0,
                forbidClick: true,
                message: '正在加载',
            });
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

http.interceptors.response.use(
    (response) => {
        Toast.clear();
        const res = response.data;
        if (res.code === 403) {
            Notify({ type: 'danger', message: res.message });
            clear();
            router.push("/login");
        } else if (res.code !== 200) {
            Notify({ type: 'danger', message: res.message });
        }
        return response;
    },
    (error) => {
        Toast.clear();
        Notify({ type: 'danger', message: "请求失败" });
        return Promise.reject(error);
    }
);

function request(options) {
    return new Promise(resolve => {
        http(options).then(res => {
            resolve(res.data);
        });
    });
}

window.request = request;

export default request;
